//
//  AsyncImageView.m
//  nonghubao
//
//  Created by 王 文彬 on 13-3-12.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "ASImageView.h"
#import "UIImageView+WebCache.h"
#import "Helper.h"
#import <QuartzCore/QuartzCore.h>


@implementation ASImageView

@synthesize image = _image;
@synthesize sourceURL = _sourceURL;
@synthesize imageView = _imageView;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //背景
        self.backgroundColor = [UIColor whiteColor];
        
        //实例化子视图
        _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        
        [_imageView setUserInteractionEnabled:YES];
        [self addSubview:_imageView];
    }
    return self;
}



//
- (void)setImage:(UIImage *)image
{
    _image = image;
    _imageView.image = _image;
    
    //如果image为空，就直接隐藏_imageView，并为其image属性赋值nil。
    //算法：这个操作用于兼容UIImageView将image设置为nil，不显示图片的操作
    if (image == nil) {
        self.hidden = true;
    }
    else {
        self.hidden = false;
        CGSize size = [Helper sizeOfImage:image forStyle:_pictureStyle];
        
        //绘出图片
        //算法：先计算_imageView在self中的位置（根据_image.size）。
        //     注意，一定要用self.frame.size来计算_imageView.frame，以使被复用的实例中的_imageView.frame得到重新计算
        _imageView.frame = CGRectMake((self.frame.size.width - size.width) / 2, (self.frame.size.height - size.height) / 2, size.width, size.height);
    }
}


// 设置图片的URL
- (void)setImageURL:(NSURL *)URL andSourceImageURL:(NSURL *)sourceURL forStyle:(PictureStyle)style
{
    _pictureStyle = style;
    _sourceURL    = sourceURL;

    if (URL == nil) {
        return;
    }

    if (sourceURL != nil) {
        _mediaManager = [[ASMediaFocusManager alloc] init];
        _mediaManager.delegate = self;
        [_mediaManager installOnView:_imageView];
        _mediaManager.sourceURL = sourceURL;
    }

//    self.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:URL]];
//    return;
    
    //把自己转移成__block修饰的变量，以保证在BLOCK中不背retain
    __block ASImageView* selfView = self;
    
    //载入图片
    [_imageView setImageWithURL:URL placeholderImage:nil options:SDWebImageProgressiveDownload completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
        
        if (error == nil) {
            //调用setImage方法，绘出图片
            selfView.image = image;
        }
        else {
            NSLog(@"error%@ %@", error, URL);
        }
    }];
    
    
}


// 设定样式
- (void)setBorderWithColor:(UIColor *)color andWidth:(float)width
{
    self.layer.borderWidth = width;
    self.layer.borderColor = [color CGColor];
}


#pragma mark - ASMediaFocusDelegate
// Returns an image that represents the media view. This image is used in the focusing animation view.
// It is usually a small image.
- (UIImage *)mediaFocusManager:(ASMediaFocusManager *)mediaFocusManager imageForView:(UIView *)view
{
    return _image;
}

@end
